package com.lsl.rdf.aop;

import com.lsl.rdf.annotation.LockSimple;
import com.lsl.rdf.distributedLock.DistributedLock;
import com.lsl.rdf.lock.LockWaitOverTimeException;
import com.lsl.rdf.utils.LockAopUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.util.Assert;

/**
 * Created by lsl on 2021/4/27.
 */
@Aspect
@Slf4j
@Order(999)
public class SimpleDistributedLockAop {

    @Autowired
    private DistributedLock distributedLock;

    @Pointcut("@annotation(com.lsl.rdf.annotation.LockSimple)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object doLock(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result;

        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();

        LockSimple lockSimple = methodSignature.getMethod().getAnnotation(LockSimple.class);

        int waitSeconds = lockSimple.waitSeconds();
        int overtimeSeconds = lockSimple.overtimeSeconds();
        boolean fairLock = lockSimple.fairLock();
        String el = lockSimple.el();

        String lockName = LockAopUtil.getLockName(joinPoint, el);

        if (this.getLock(lockName, waitSeconds, overtimeSeconds, fairLock)) {
            try {
                result = joinPoint.proceed();
            } finally {
                if (fairLock) {
                    distributedLock.releaseFairLock(lockName);
                } else {
                    distributedLock.releaseLock(lockName);
                }
            }
        } else {
            log.warn("SimpleDLockAop.doLock 等待锁超时. lockName: {}, waitSeconds: {}, overtimeSeconds: {}", lockName, waitSeconds, overtimeSeconds);
            throw new LockWaitOverTimeException(String.format("等待锁超时！ lockName: %s, waitSeconds: %s", lockName, waitSeconds));
        }
        return result;
    }

    /**
     * 获取锁
     *
     * @param lockName        所名称
     * @param waitSeconds     等待锁时间
     * @param overtimeSeconds 锁超时时间
     * @param isFairLock      是否公平锁
     * @return 锁
     */
    private boolean getLock(String lockName, int waitSeconds, int overtimeSeconds, boolean isFairLock) {
        Assert.notNull(lockName, "SimpleDLockAop.getLock 获取锁失败 lockName 为空");
        boolean lock;
        if (isFairLock) {
            lock = distributedLock.acquireFairLock(lockName, waitSeconds, overtimeSeconds);
        } else {
            lock = distributedLock.acquireLock(lockName, waitSeconds, overtimeSeconds);
        }
        return lock;
    }
}
